package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

@Service
public class MqttPublishServer {
    @Autowired
    private MqttPahoClientFactory clientFactory;

    @Value("${spring.mqtt.client-id}")
    private String clientId;

    public void publish(String topic, String payload, int qos) {
        try {
            MqttPahoMessageHandler handler = new MqttPahoMessageHandler(
                    clientId,
                    clientFactory
            );
            handler.setAsync(true);
            handler.setDefaultTopic(topic);
            handler.setDefaultQos(qos);
            handler.handleMessage(new GenericMessage<>(payload));
        } catch (Exception e) {
            throw new RuntimeException("MQTT发布失败: " + e.getMessage(), e);
        }
    }
}
